package com.canal.display.service.impl;

import com.canal.display.dao.ZcolBusRecordMapper;
import com.canal.display.dao.ZcolChannelMapper;
import com.canal.display.entity.canal.ZcolChannel;
import com.canal.display.exception.BuzException;
import com.canal.display.service.ZcolChannelService;
import com.canal.display.transfer.req.RecordConditions;
import com.canal.display.transfer.req.RestPwdReq;
import com.canal.display.transfer.resp.CanalRecordResp;
import com.canal.display.transfer.resp.PageResp;
import com.canal.display.util.PageUtil;
import com.canal.display.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author yangbo
 * @date 2020-07-30 20:52
 * @description
 * @since
 */
@Service
@Slf4j
public class ZcolChannelServiceImpl implements ZcolChannelService {

    @Autowired
    private ZcolBusRecordMapper zcolBusRecordMapper;

    @Autowired
    private ZcolChannelMapper zcolChannelMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 渠道商进量查询
     * @param conditions
     * @return
     * @throws BuzException
     */
    @Override
    public PageResp recordList(RecordConditions conditions) throws BuzException {
        ZcolChannel zcolChannel = SecurityUtils.currentUser();
        if(zcolChannel == null) {
            throw new BuzException(500,"用户未登录，无法使用");
        }
        PageHelper.startPage(conditions.getPageNo(),conditions.getPageSize());
        List<CanalRecordResp> respList = zcolBusRecordMapper.findListByConditions(conditions,zcolChannel.getId());
        PageInfo<CanalRecordResp> pageInfo = new PageInfo<>(respList);
        PageResp pageResp = PageUtil.toResp(pageInfo);
        return pageResp;
    }

    /**
     * 更新密码
     * @param req
     * @param channelId
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(RestPwdReq req, Integer channelId) throws BuzException {
        //校验原密码
        ZcolChannel zcolChannel = zcolChannelMapper.findById(channelId);
        String buzPassword = zcolChannel.getBuzPassword();
        if(!passwordEncoder.matches(req.getOldPwd(),buzPassword)) {
            throw new BuzException(500,"原密码错误");
        }
        //更新密码
        zcolChannel.setBuzPassword(passwordEncoder.encode(req.getNewPwd()));
        zcolChannelMapper.updatePwd(zcolChannel);
    }
}
